const nTubeTV = {};
nTubeTV.init = function () {
	run_async(function () {
		id("-system-ui-about-buttom-menu").onclick = function () {
			hide(id("-ui-section-home"));
			show(id("-ui-section-about"));
		};
	});
	run_async(function () {
		id("-system-ui-home-buttom-menu").onclick = function () {
			hide(id("-ui-section-about"));
			show(id("-ui-section-home"));
		};
	});
	run_async(function () {
		id("_js_supported").innerHTML = "SUPPORTED";
		id("_js_supported").style.color = "green";
		if (window && window.navigator && window.navigator.cookieEnabled && window.navigator.cookieEnabled === true) {
			id("_ck_supported").innerHTML = "SUPPORTED";
			id("_ck_supported").style.color = "green";
		}
		if (typeof Storage === "function" || typeof Storage === "object") {
			id("_ls_supported").innerHTML = "SUPPORTED";
			id("_ls_supported").style.color = "green";
		}
		if (typeof document.createElement("video").canPlayType != "undefined") {
			id("_vid_supported").innerHTML = "SUPPORTED";
			id("_vid_supported").style.color = "green";
		}
		id("-ui-system-about-user-agent").innerText = navigator.userAgent;
	});
	console.debug("nTube for TV, ready.");
};
nTubeTV.do_trending = function () {
	id("trending-items").innerHTML = "";
	request(
		"/api/get_trending",
		null,
		function (error) {
			alert("Failed to get trending videos.\nCheck your browser console for more info.");
			console.error(error);
		},
		function (data) {
			var o = JSON.parse(data);
			var items = o["items"];
			const ti = id("trending-items");
			for (var _i = 0; _i < items.length; _i++) {
				const i = _i;
				const item = items[i];
				var c = document.createElement("div");
				c.classList.add("trending-div", "poly-item");
				var a = document.createElement("a");
				a.href = item.url; //
				a.classList.add("trending-link");
				c.appendChild(a);
				const img = document.createElement("img");
				img.classList.add("trending-img");
				img.src = item.img_url;
				if (item.anim_img_url && item.anim_img_url !== null) {
					img.onmouseover = function () {
						img.src = item.anim_img_url;
					};
					img.onmouseout = function () {
						img.src = item.img_url;
					};
				}
				a.appendChild(img);
				var d = document.createElement("div");
				d.style.display = "inline-block";
				d.style.verticalAlign = "middle";
				a.appendChild(d);
				var title = document.createElement("p");
				title.style.verticalAlign = "top";
				title.style.textAlign = "left";
				title.style.fontWeight = "bold";
				title.style.fontSize = "large";
				title.style.marginLeft = "5px";
				title.innerHTML = item["title"];
				d.appendChild(title);
				var nt = document.createElement("p");
				nt.style.verticalAlign = "bottom";
				nt.style.textAlign = "left";
				nt.style.fontSize = "small";
				nt.style.lineHeight = "20%";
				nt.style.fontStyle = "italic";
				nt.style.marginLeft = "5px";
				nt.innerHTML = "Number " + (i + 1) + " on trending.";
				d.appendChild(nt);
				var st = document.createElement("p");
				st.style.verticalAlign = "bottom";
				st.style.textAlign = "left";
				st.style.fontSize = "small";
				st.style.marginLeft = "5px";
				st.innerHTML = '<a style="color: inherit; text-decoration: underline dotted gray;" href="' + "/channel?c=" + item["channel_id"] + '">' + item["author"] + "</a>";
				if (item["author_verified"]) {
					st.innerHTML += '<b class="user-verified" title="This user is verified.">&check;</b>';
				}
				st.innerHTML += " &centerdot; ";
				st.innerHTML += item["duration"];
				d.appendChild(st);
				ti.appendChild(c);
			}
		}
	);
};
nTubeTV.loadVideo = function () {
	const __args = arguments;
	if (arguments.length <= 0) {
		throw new Error("E:INVALID_ARGUMENT_COUNT");
	}
	var PLAYBACK_ENGINE = "stub";
	var PREFER_QUALITY = 0;
	var allowWebM = true;
	var av1Action = "def";
	const videoID = __args[0];
	function allowAV1() {
		if (av1Action === "def") {
			if (isBattery()) return false;
			return supportsAV1playback() || getQueryVariable("av1") !== null;
		} else {
			return av1Action === "fon";
		}
	}
	function getUTCOffset() {
		if (window.Date && window.Date.prototype.getTimezoneOffset) {
			return new Date().getTimezoneOffset();
		} else {
			return 120;
		}
	}
	const jxr = {
		next_api_version: 2,
		videoID: videoID,
		enableAV1: allowAV1(),
		enableWebM: allowWebM || getQueryVariable("allowWebM") !== null,
		enableDashJS: PLAYBACK_ENGINE === "videojs-dash" || PLAYBACK_ENGINE === "dash.js" || PLAYBACK_ENGINE === "plyr-dash" || PLAYBACK_ENGINE === "shaka" || PLAYBACK_ENGINE === "shaka+ui" || PLAYBACK_ENGINE === "rxplayer",
		dashJSUseCompression: false,
		dashJSAllowCaching: true,
		preferredQuality: PREFER_QUALITY,
		systemInfo: {
			utcTimezoneOffset: getUTCOffset(),
		},
		telemetry: {
			h264: supportsVideoType("h264") === "probably",
			vp9: supportsVideoType("vp9") === "probably",
			av1: supportsAV1playback(),
			client: libWeb.BrowserEnvironment.getBrowserVersion(),
			frontend: "ntube-tv",
		},
	};
	const __url = "/api/get_video?v=" + videoID;
	request(
		__url,
		JSON.stringify(jxr),
		function (exception) {
			console.error(exception);
			alert("nTube failed to talk with it's backend.\r\nCheck your browser's console for more information.");
		},
		function (data) {
			const jsonObject = JSON.parse(data);
			if (jsonObject.error_id) {
				var error_id = jsonObject.error_id;
				if (error_id === "ERROR_UPCOMING_STREAM") {
					id("-ui-system-video-title").innerHTML = jsonObject.metadata.title;
					id("-ui-system-video-author").innerHTML = jsonObject.metadata.author;
					/* TODO: Trigger countdown for stream here. */
				} else if (error_id === "FAILED_STAGE_UNABLE_TO_GET_METADATA") {
					/* TODO: Add an error popup a-la nintendo switch style, idk. */
				} else {
					console.error("nTube: Failed to extract! Error: " + jsonObject.error_id);
					if (jsonObject.error) {
						console.error(jsonObject.error);
						alert("nTube: Internal error occurred during extraction.\n\n" + jsonObject.error);
					} else {
						console.error(jsonObject.error_message);
						alert("nTube: Internal error occurred during extraction.\n\n" + jsonObject.error_message);
					}
				}
				return;
			} else {
				id("-ui-system-video-title").innerHTML = jsonObject.metadata.title;
				id("-ui-system-video-author").innerHTML = jsonObject.metadata.author;
				id("-ui-system-video-player-main").src = jsonObject.videos.combinedStreams[jsonObject.videos.preferred.comb].proxied_url;
			}
		}
	);
};
window.nTubeTV = nTubeTV;
